package com.example.order.listener;

import com.example.order.event.OrderCancelledEvent;
import com.example.order.event.OrderCreatedEvent;
import com.example.order.event.OrderPaidEvent;
import com.example.order.metrics.BusinessMetrics;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

/**
 * 订单事件监听器，负责处理订单相关事件并更新监控指标
 */
@Component
public class OrderEventListener {
    private static final Logger logger = LoggerFactory.getLogger(OrderEventListener.class);
    private final BusinessMetrics businessMetrics;

    public OrderEventListener(BusinessMetrics businessMetrics) {
        this.businessMetrics = businessMetrics;
    }

    /**
     * 处理订单创建事件
     */
    @EventListener
    public void handleOrderCreatedEvent(OrderCreatedEvent event) {
        logger.info("处理订单创建事件: {}", event.getOrderNo());
        
        // 更新订单状态指标
        businessMetrics.incrementOrderStatus("created");
        
        // 更新订单金额指标
        businessMetrics.addOrderAmount(event.getAmount());
    }

    /**
     * 处理订单支付事件
     */
    @EventListener
    public void handleOrderPaidEvent(OrderPaidEvent event) {
        logger.info("处理订单支付事件: {}", event.getOrderNo());
        
        // 更新订单状态指标
        businessMetrics.incrementOrderStatus("paid");
        
        // 更新支付方式指标
        businessMetrics.incrementPaymentMethod(event.getPaymentMethod());
        
        // 记录支付处理时间
        businessMetrics.recordPaymentProcessingTime(event.getPaymentDurationSeconds());
    }

    /**
     * 处理订单取消事件
     */
    @EventListener
    public void handleOrderCancelledEvent(OrderCancelledEvent event) {
        logger.info("处理订单取消事件: {}", event.getOrderNo());
        
        // 更新订单状态指标
        businessMetrics.incrementOrderStatus("cancelled");
    }
}
